package com.fitz.core.util;

import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * 描    述：
 * 创 建 者：gousili
 * 修 改 者：
 * 创建时间：2021-03-20 16:58
 */
public class OkHttpUtil {
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String CONTENT_TYPE = "Content-Type";
    //超时时间
    public static final int TIMEOUT= 1000 * 60;
    private static OkHttpClient okHttpClient;
    private Request.Builder requestBuilder;
    private static OkHttpUtil instance;
    private OkHttpUtil(){
        okHttpClient = new OkHttpClient.Builder()
                .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .build();
        requestBuilder = new Request.Builder();
    }
    public static synchronized OkHttpUtil getInstance(){
        if(instance == null) {
            instance = new OkHttpUtil();
        }
        return instance;
    }
    /**
     * 同步请求
     * @param request
     * @return
     * @throws IOException
     */
    public  Response execute(Request request) throws IOException {
        return okHttpClient.newCall(request).execute();
    }
    /**
     * 同步get请求
     * @param url
     * @param paramsMap
     * @return
     * @throws IOException
     */
    public String get(String url, HashMap<String,String> paramsMap) throws IOException {
        StringBuilder params = parseParams(paramsMap);
        String requestUrl = String.format("%s?%s", url, params);
        Request request = new Request.Builder().url(requestUrl).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
    /**
     * 同步get请求
     * @param url
     * @param
     * @return
     * @throws IOException
     */
    public String get(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public String executeWithJson(String url, String requestString, HashMap<String,String> header, String method) throws IOException {
        RequestBody requestBody = null;
        if (StringUtils.isBlank(requestString)){
            requestBody = RequestBody.create(null, "");
        }else {
            requestBody = RequestBody.create(MEDIA_TYPE_JSON, requestString);
        }
        Request.Builder requestBuilder = new Request.Builder();
        Headers.Builder headers = new Headers.Builder();
        if (header !=null&&header.size()>0){
            Iterator iterator = header.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry entry = (Map.Entry) iterator.next();
                headers.add((String) entry.getKey(), (String) entry.getValue());
            }
            headers.add(CONTENT_TYPE,"application/json");
            requestBuilder.headers(headers.build());
        }
        Request request = null;
        switch (method){
            case "POST":
                request = requestBuilder.url(url).post(requestBody).build();
                break;
            case "PUT":
                request = requestBuilder.url(url).put(requestBody).build();
                break;
            case "DELETE":
                request = requestBuilder.url(url).delete(requestBody).build();
                break;
        }
        Response response = execute(request);
        if (response.isSuccessful()) {
            String result = response.body().string();
            return result;
            //只能调用一次,因为读取后就关闭并释放资源了
        }
        return null;
    }
    /**
     * 格式化参数
     * @param paramsMap
     * @return
     * @throws UnsupportedEncodingException
     */
    private StringBuilder parseParams(HashMap<String, String> paramsMap) throws UnsupportedEncodingException {
        StringBuilder params = new StringBuilder();
        int pos = 0;
        for (String key : paramsMap.keySet()) {
            if (pos > 0) {
                params.append("&");
            }
            params.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8")));
            pos++;
        }
        return params;
    }

}